package com.feiyisys.interceptors;

import com.feiyisys.annotation.AdminRequired;
import com.feiyisys.entity.Admin;
import com.feiyisys.service.AdminService;
import com.feiyisys.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;

/**
 * 管理员权限验证拦截器
 * 用于验证标注了@AdminRequired注解的接口
 */
@Slf4j
@Component
public class AdminAuthInterceptor implements HandlerInterceptor {

    @Resource
    private AdminService adminService;
    
    @Resource
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断是否是HandlerMethod
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        // 检查方法是否标注了AdminRequired注解
        if (method.isAnnotationPresent(AdminRequired.class)) {
            log.info("验证管理员权限...");
            
            // 获取token
            String token = request.getHeader("Authorization");
            if (token == null) {
                response.setStatus(403);
                response.getWriter().write("需要管理员权限访问");
                return false;
            }
            
            token = token.replace("Bearer ", "");
            
            // 解析token获取用户ID
            Claims claims = jwtUtil.parseToken(token);
            Long userId = claims.get("id", Long.class);
            
            // 尝试从admin表中查询，如果存在则为管理员
            Admin admin = adminService.getById(userId);
            if (admin == null) {
                response.setStatus(403);
                response.getWriter().write("需要管理员权限访问");
                return false;
            }
            
            log.info("管理员权限验证通过，用户ID: {}", userId);
        }
        
        return true;
    }
}